package com.liuzhilong.infrastructure.basic.jdk.thread;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * 测试线程组的使用方式
 */
public class ThreadGroupUse {

    private static final ThreadGroup createMyThreadGroup(){
        return new ThreadGroup("MyThread"){
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println(t.getName()+"-出现异常"+e.getMessage());
//                super.uncaughtException(t, e);
            }
        };
    }



    @SneakyThrows
    public static void main(String[] args) {
        ThreadGroup threadGroup = createMyThreadGroup();
        int treadCount = 0;
        new Thread(threadGroup,createRunable(500,5000),"test"+treadCount++).start();
        new Thread(threadGroup,createRunable(1000,10000),"test"+treadCount++).start();
        new Thread(threadGroup,createRunable(2000,10000),"test"+treadCount++).start();
        new Thread(threadGroup,createRunable(3000,10000),"test"+treadCount++).start();
        new Thread(threadGroup,createRunable(1000,10000),"test"+treadCount++).start();
        new Thread(threadGroup,()->{},"test"+treadCount++).start();
        threadGroup.setDaemon(true);
        threadGroup.setMaxPriority(Integer.MAX_VALUE);
        //等待7秒之后，输出存活并关闭所有
        Thread.sleep(7*1000);
        System.out.println(threadGroup.activeCount());
        threadGroup.interrupt();
    }


    public static final Runnable createRunable(long wait,long alivedTime){
        Random r=new Random();
        return ()->{
            String name = Thread.currentThread().getName();
            long start = System.currentTimeMillis();
            int count = 0;
            System.out.println(name+"-启动");

            while (System.currentTimeMillis()-start<alivedTime){

                if(r.nextInt(20)==2){
                    throw new RuntimeException("测试模拟异常");
                }


                try {
                    Thread.sleep(wait);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(name+"-"+count++);
            }
            System.out.println(name+"-正常结束");
        };
    }
}
